package com.weiyi.mashangzhu.easemob.db;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

import com.hyphenate.easeui.widget.chatrow.SdCard;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Utils.Md5Utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class ChatDao {

    public static final String TABLE_NAME = "personal";
    public static final String ACCOUNT = "account";
    public static final String NICK = "nick";
    public static final String AVATAR = "avatar";
    public static final String EXT = ".jpg";
    private Context context;
    private Bitmap bitmap;

    public ChatDao(Context context) {
        this.context = context;
    }

    public void add(String account, String nick, String avatar) {
        headBitmap(avatar);
        ChatManager.getInstance().add(account, nick, convertFileName(avatar));
    }

    public void delete(String account) {
        ChatManager.getInstance().delete(account);
    }

    public void update(String account, String nick, String avatar) {
        String tagNick = nick;
        String tagAvatar = convertFileName(avatar);
        if (!"".equals(tagNick) || !"".equals(tagAvatar)) {
            String[] find = findByAccount(account);
            if (find != null && find.length > 0) {
                if (tagNick != null) {
                    if (tagNick.equals(find[0])) {
                        tagNick = "";
                    }
                } else {
                    tagNick = "";
                }
                if (tagAvatar != null) {
                    if (tagAvatar.equals(find[1])) {
                        tagAvatar = "";
                    } else {
                        headBitmap(avatar);
                    }
                } else {
                    tagAvatar = "";
                }
            }
            ChatManager.getInstance().update(account, tagNick, tagAvatar);
        }
    }

    public boolean isExist(String account) {
        return ChatManager.getInstance().isExist(account);
    }

    public String[] findByAccount(String account) {
        return ChatManager.getInstance().findByAccount(account);
    }

    public List<ChatBean> findAll() {
        return ChatManager.getInstance().findAll();
    }

    public String convertFileName(String head) {
        return !"".equals(head) ? Md5Utils.getEncryption(head) : "";
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    saveFile((String) msg.obj);
                    break;
                case 2:
                    saveFile_share((String) msg.obj);
                    break;
            }
        }
    };

    private void saveFile(String url) {
        try {
            File file = new File(SdCard.SAVE_PATH);
            if (!file.exists()) {
                file.mkdirs();
            }
            File captureFile = new File(SdCard.SAVE_PATH, convertFileName(url) + EXT);
            if (!captureFile.exists()) {
                captureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(captureFile));
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            }
            bos.flush();
            bos.close();
            SystemClock.sleep(1000);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(captureFile);
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {

        }
    }
    private void saveFile_share(String url) {
        String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/com.weiyi.mashangzhu/share";
        try {
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            File captureFile = new File(savePath,"share" + EXT);
            if (!captureFile.exists()) {
                captureFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(captureFile));
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
            }
            bos.flush();
            bos.close();
            SystemClock.sleep(1000);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(captureFile);
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {

        }
    }

    public void headBitmap(final String url) {
        new Thread() {
            @Override
            public void run() {
                if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
                    try {
                        URL fileUrl = new URL(API.BaseApi_url + url);
                        HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
                        conn.setDoInput(true);
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = url;
                        handler.sendMessage(msg);
                    } catch (IOException e) {

                    }
                }
            }
        }.start();
    }
    public void headBitmap_share(final String url) {
        new Thread() {
            @Override
            public void run() {
                if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
                    try {
                        URL fileUrl = new URL(API.BaseApi_url + url);
                        HttpURLConnection conn = (HttpURLConnection) fileUrl.openConnection();
                        conn.setDoInput(true);
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        bitmap = BitmapFactory.decodeStream(is);
                        is.close();
                        Message msg = new Message();
                        msg.what = 2;
                        msg.obj = url;
                        handler.sendMessage(msg);
                    } catch (IOException e) {

                    }
                }
            }
        }.start();
    }
}
